#include "../../include/unm.h"
#include <git2.h>
#include <iostream>

namespace unm {

bool GitNodeManager::addGitRepository(const std::string& path) {
    git_repository* repo = nullptr;
    int error = git_repository_open(&repo, path.c_str());
    if (error < 0) {
        std::cerr << "无法打开Git仓库: " << path << std::endl;
        return false;
    }
    
    Node repo_node;
    repo_node.id = "git:" + path;
    repo_node.type = NODE_GIT_REPO;
    repo_node.uri = path;
    
    // 提取Git仓库特征
    extractGitFeatures(repo_node);
    
    addNode(repo_node);
    
    std::cout << "已添加Git仓库: " << path << std::endl;
    
    // 分析子模块
    analyzeSubmodules(path);
    
    git_repository_free(repo);
    return true;
}

int GitNodeManager::submoduleCallback(git_submodule* sm, const char* name, void* payload) {
    auto* manager = static_cast<GitNodeManager*>(payload);
    
    const char* submodule_url = git_submodule_url(sm);
    if (submodule_url) {
        // 创建子模块节点
        Node submodule_node;
        submodule_node.id = std::string("git_submodule:") + submodule_url;
        submodule_node.type = NODE_GIT_REPO;
        submodule_node.uri = submodule_url;
        
        manager->addNode(submodule_node);
        
        // 创建依赖关系
        Relation dep_rel;
        dep_rel.source_id = "git:" + std::string(name);
        dep_rel.target_id = submodule_node.id;
        dep_rel.type = REL_DEPENDENCY;
        manager->addRelation(dep_rel);
        
        std::cout << "发现子模块: " << name << " -> " << submodule_url << std::endl;
    }
    
    return 0;
}

bool GitNodeManager::analyzeSubmodules(const std::string& repo_path) {
    git_repository* repo = nullptr;
    int error = git_repository_open(&repo, repo_path.c_str());
    if (error < 0) {
        return false;
    }
    
    git_submodule_foreach(repo, submoduleCallback, this);
    
    git_repository_free(repo);
    return true;
}

std::vector<std::string> GitNodeManager::findMirrorRepositories(const std::string& repo_url) {
    std::vector<std::string> mirrors;
    
    // 基于URL模式生成可能的镜像
    std::vector<std::string> mirror_patterns = {
        "https://gitee.com/mirrors/{repo}",
        "https://gitee.com/uesoft/{repo}",
        "https://gitcode.com/mirrors/{repo}",
        "https://mirrors.huaweicloud.com/{repo}"
    };
    
    // 提取仓库名
    size_t last_slash = repo_url.find_last_of('/');
    if (last_slash != std::string::npos) {
        std::string repo_name = repo_url.substr(last_slash + 1);
        
        for (const auto& pattern : mirror_patterns) {
            std::string mirror_url = pattern;
            size_t pos = mirror_url.find("{repo}");
            if (pos != std::string::npos) {
                mirror_url.replace(pos, 6, repo_name);
                mirrors.push_back(mirror_url);
            }
        }
    }
    
    return mirrors;
}
}
